package com.boxin.ims.modules.momarketing.web.front;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boxin.ims.modules.momarketing.entity.Coupon;
import com.boxin.ims.modules.momarketing.entity.CouponConfig;
import com.boxin.ims.modules.momarketing.service.CouponConfigService;
import com.boxin.ims.modules.momarketing.service.CouponService;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;


/**
 * @author Jakemanse
 * @date 2013-9-6
 * @function <p> 优惠券核销</p>
 */


@Controller
@RequestMapping(value= Global.MOBILE_SITE_PATH + "/consume")
public class CouponFrontController extends BaseController {
	
	@Autowired
	CouponService couponService;
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	CouponConfigService couponConfigService;
	
	
	
	@RequestMapping(value = "/{number}")
	public String consume(@PathVariable String number,HttpServletRequest request,HttpServletResponse response){
		
		String username = request.getParameter("username");
		String ternimalNumber = request.getParameter("tNumber");
		
		Coupon coupon = couponService.getByNumber(number);
		User user = UserUtils.getUserByUsername(username);
		Map<String,String> param = new HashMap<String,String>();
		
		String xml = "";
		if(coupon != null){
			if(Coupon.CANCEL_FLAG_DELETE.equals(coupon.getStatus())){
				xml = wrapXML(false,"该优惠券已消费过","该优惠券已消费过!");
			}else{
				coupon.setStatus(Coupon.CANCEL_FLAG_DELETE);
				coupon.setRemarks("核销人:"+user.getName() +",终端号:"+ternimalNumber);
				couponService.save(coupon);
				xml = wrapXML(true,"该优惠券已消费过","核销成功!");
				
				//添加核销  加积分处理
				if(Coupon.SOURCE_TYPE_WP.equals(coupon.getSourceType())){
					WechatMember member = wechatMemberService.getByWechatMemberId(user, coupon.getSourceId());
					if(member != null){
						CouponConfig config = 	couponConfigService.get(coupon.getConfig().getId());
						int addScore = (config == null) ? 0 : config.getMemberScore();
						Integer score = member.getScore();
						score = (score==null) ? 0 : score + addScore;
						member.setScore(score);
						wechatMemberService.save(member);
						//积分流水记录
						ScoreUtils.addWechatMemberCouponScore(member, coupon,addScore);	//积分记录
					}
				}
				
			}
		}else{
			xml = wrapXML(false,"未找到该优惠券的电子凭证信息,核销失败!","核销失败");
		}
		
		responseXML(request, response, xml);
		return null;
	}
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-6  上午10:17:14
	 * @function <p> 获取注册的 终瑞号码 </p>
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "tmn" + Global.URL_SUFFIX)
	public void generateTNumber(HttpServletRequest request,HttpServletResponse response){
		String username = request.getParameter("username");
		String pwd = request.getParameter("password");
		
		User user = UserUtils.getUserByUsername(username);
		Map<String,String> param = new HashMap<String,String>();
		String xml = "";
		if(user != null ){
			if(pwd!=null){
				String enpwd  = SystemService.entryptPassword(pwd);
				if(enpwd.equals(user.getPassword())){	//验证通过生成 端终序列事情
					String terminalNumber = "" + System.currentTimeMillis();
					param.put("terminalNumber", terminalNumber);
					wrapXML(true,"","已核销");
				}
			}
		}else{
			wrapXML(false,"","核销失败");
		}
		
		
		
		responseXML(request, response, xml);
	}
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-7  上午12:50:21
	 * @function <p>  </p>
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "login")
	public void login(HttpServletRequest request,HttpServletResponse response){
		String username = request.getParameter("username");
		String pwd = request.getParameter("password");
		
		User user = UserUtils.getUserByUsername(username);
		String xml = wrapXML(false,"","登录失败");;
		if(user != null ){
			if(pwd!=null){ 
				String enpwd  = SystemService.entryptPassword(pwd);
				if(enpwd.equals(user.getPassword())){	//验证通过生成 端终序列事情
					String terminalNumber = "" + System.currentTimeMillis();
					xml = wrapXML(true,"","登录成功。");
				}
			}
		}else{
			xml = wrapXML(false,"失败,该帐号["+username+"]不存在！","登录失败");
		}
		
		responseXML(request, response, xml);
	}
	
	
	
	private String wrapXML(boolean success,String errorInfo,String tip){
		
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>").append("\r\n");
		xml.append("<response>").append("\r\n");
		xml.append("\t<success>").append(success).append("</success>").append("\r\n");
		xml.append("\t<errorInfo>").append(errorInfo).append("</errorInfo>").append("\r\n");
		xml.append("\t<tip>").append(tip).append("</tip>").append("\r\n");
		xml.append("<response>");
		return xml.toString();
		
	}
	

}
